import json
import logging
import os
import threading
import time

import django
from nacos import NacosClient

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nacos_gateway.settings')


class AutoRouter:
    def __init__(self, host, port, namespaceId):
        django.setup(set_prefix=False)
        self.host = host
        self.port = port
        self.nacos_client = NacosClient('http://192.168.222.128', 8848)
        self.nacos_client.instance().register(self.host, self.port, serviceName='gateway',
                                              namespaceId=namespaceId)
        self.nacos_client.instance().auto_beat(self.host, self.port, serviceName='gateway',
                                               namespaceId=namespaceId)
        r_reload = threading.Thread(target=self.router_reload)
        r_reload.setDaemon(True)
        r_reload.start()

    def router_reload(self):
        def reload():
            try:
                from apps.forward.models import ForwardConfig
                namespace_list_dict = json.loads(self.nacos_client.namespace().list())
                if namespace_list_dict:
                    namespace_list = namespace_list_dict.get('data')
                    for namespace in namespace_list:
                        service_list = json.loads(self.nacos_client.service().list(pageNo=1, pageSize=1024,
                                                                                   namespaceId=namespace.get(
                                                                                       'namespace')))
                        if service_list:
                            for service in service_list.get('doms', []):
                                hosts = json.loads(
                                    self.nacos_client.instance().list(serviceName=service, namespaceId=namespace.get(
                                        'namespace')))
                                forward_config = ForwardConfig.objects.filter(
                                    namespace=namespace.get('namespace', 'public'),
                                    service_name=service).first()
                                if not forward_config:
                                    ForwardConfig(namespace=namespace.get('namespace', 'public'), service_name=service,
                                                  hosts=json.dumps(hosts.get('hosts')), checksum=hosts.get('checksum')).save()
                                else:
                                    if forward_config.checksum != hosts.get('checksum'):
                                        forward_config.hosts = json.dumps(hosts.get('hosts'))
                                        forward_config.checksum = hosts.get('checksum')
                                        forward_config.save()

            except Exception as e:
                logger = logging.getLogger('django')
                logger.error(e.__str__())
                pass
        while True:
            reload()
            time.sleep(20)
